import * as jose from 'jose'

export async function verifyToken(token: string) {
  try {
    const secret = new TextEncoder().encode(process.env.JWT_SECRET)
    const { payload } = await jose.jwtVerify(token, secret)

    return {
      valid: true,
      data: payload
    }
  } catch (error) {
    console.error('Token verification error:', error)
    if ((error as Error).name === 'JWTExpired') {
      return {
        valid: false,
        error: 'token_expired',
        message: 'Token已过期，请重新登录'
      }
    }
    return {
      valid: false,
      error: 'invalid_token',
      message: 'Token无效'
    }
  }
}

export async function getCurrentUser(token: string) {
  try {
    console.log(token, 32)

    const secret = new TextEncoder().encode(process.env.JWT_SECRET)
    const { payload } = await jose.jwtVerify(token, secret)
    console.log('decoded token:', payload)
    return payload
  } catch (error) {
    console.error('Token verification failed:', error)
    return null
  }
}

// 获取当前用户ID的快捷方法
export async function getCurrentUserId(token: string) {
  const user = await getCurrentUser(token)
  return user?.id as number
}
